let bx = 1240 / device.width
let by = 2772 / device.height
//设置控制台
setConsole()
function init() {
    //获取悬浮窗权限
    auto.waitFor()
    //打开录屏权限
    getScreenCapture()
    //设置屏幕宽高
    setScreenMetrics(1240, 2772)

}

//进入抖音首页
function enterDouYinIndex() {
    if (tool.getText('首页') !== null && tool.getText('消息') !== null) {
        tool.log("进入首页")
        if (tool.clickTextByScreenCapture("首页")) {
            tool.log("点击首页")
            sleep(3000)
        } else {
            enterDouYinIndex()
        }
    } else {
        back()
        tool.log("返回")
        sleep(2000)
        enterDouYinIndex()
    }
}

var win;
//设置控制台
function setConsole() {
    win = floaty.rawWindow(
        <vertical h="200" w="150" bg="#000000" alpha="0.4">
            <text id="log" line="10" textColor="white" textSize="14sp" typeface="normal"></text>
        </vertical>
    );
    //悬浮穿透
    win.setTouchable(false);
    //悬浮移动
    win.setPosition(device.width - 500, 0)
}

//输出日志到控制台
function log(str) {
    threads.start(() => {
        console.log(str)
        ui.run(() => {
            try {
                let t = win.log.text()
                let size = t.split("\n")
                let v = ""
                let maxLine = 10
                if (size.length > maxLine) {
                    for (let i = size.length - maxLine + 1; i < size.length - 1; i++) {
                        v += size[i] + "\n"
                    }
                } else {
                    v = t
                }
                v += str + "\n"
                // console.log(win.log)
                win.log.setText(v);
            } catch (e) {
                console.log("输出日志异常:" + e)
            }
        });
    })
}

function _press(x, y, time) {
    if (!time) {
        time = 100
    }
    press(x * bx, y * by, time)
}

//以图找图
function findImage(imageName, template, options) {
    let p = null;
    try {
        captureScreen(`./image/${imageName}`);
        sleep(1000);
        var zbjp = images.read(`./image/${imageName}`);
        template = images.read(`./image/${template}`);
        if (template == null) {
            tool.log("模板不存在")
        } else {
            p = images.findImage(zbjp, template, options)
        }
    }
    catch (e) {
        tool.log(`找图异常:${e}`);
    }
    return p;
}

//重启app
function restartApp(t) {
    killApp(t)
    sleep(1000)
    openApp(t)
}

//打开app
function openApp(appName) {
    tool.log("打开应用：" + appName)
    launchApp(appName);
    sleep(1000)
    if (textContains("跳过")) {
        clickText("跳过")
    }
}

//关闭app
function killApp(appName) {
    tool.log("关闭应用：" + appName)
    launchApp(appName);
    sleep(5000)
    home();
    sleep(1000)
    recents()
    sleep(1500)
    swipe(600, 1500, 600, 100, 50)
    sleep(1000)
    home();
}

//等待ID出现并点击
function clickId(ids, time) {
    try {
        time = time || 5000
        idContains(ids).findOne(5000)
        if (idContains(ids).exists()) {
            let p = idContains(ids).findOne(1000)
            if (p != null) {
                p = p.bounds()
                press(p.centerX() + 10, p.centerY(), 100);
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}

//等待文本出现并点击
function clickText(t, time) {
    try {
        time = time || 5000
        text(t).findOne(time)
        if (text(t).exists()) {
            let p = text(t).findOne(1000)
            if (p != null) {
                p = p.bounds()
                press(p.centerX() + 10, p.centerY(), 100);
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }

}

//点击类名
function clickClassName(t, time) {
    try {
        time = time || 5000
        classNameContains(t).findOne(time)
        if (classNameContains(t).exists()) {
            let p = classNameContains(t).findOne(1000)
            if (p != null) {
                p = p.bounds()
                press(p.centerX() + 10, p.centerY(), 100);
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}

//等待描述出现并点击
function clickDesc(t, time) {
    try {
        time = time || 5000
        descContains(t).findOne(time)
        if (descContains(t).exists()) {
            let p = descContains(t).findOne(1000)
            if (p != null) {
                p = p.bounds()
                // tool.log(`点击${t},X:${p.centerX() * bx + 10},Y:${p.centerY() * by}`)
                press(p.centerX() + 10, p.centerY(), 10);
                return true
            } else {
                return false
            }
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}

//获取悬浮窗和录屏权限
function getScreenCapture() {
   let Thread = threads.start(function () {
        if (!floaty.checkPermission()) {
            // 没有悬浮窗权限，提示用户并跳转请求
            toast("本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。");
            floaty.requestPermission();
            exit();
        } else {
            toastLog('已有悬浮窗权限');
            //由于系统间同意授权的文本不同，采用正则表达式
        }

        let Allow = textMatches(/(允许|立即开始|统一)/).findOne(10 * 1000);
        if (Allow) {
            Allow.click();
        }

    });


    if (!requestScreenCapture(false)) {
        log("请求录屏权限失败");
        return false;
    } else {
        Thread.interrupt()
        log("已获得录屏权限");
        return true;
    }

}


//系统提示音
function playRingtone(time, size) {
    var size = size || 6
    var time = time || 1000
    var musice = android.media.RingtoneManager.TYPE_NOTIFICATION
    var mp = new android.media.MediaPlayer(); device.setMusicVolume(size)
    mp.setDataSource(context, android.media.RingtoneManager.getDefaultUri(musice));
    mp.prepare();
    mp.start();
}

//检测关闭悬浮窗
function closeCoupon() {
    let option = {
        "region": [0, device.height / 4, device.width, device.height / 4 * 3],
        "threshold": 0.5
    }
    if (handleLotteryResult()) {
        return
    }
    let p = findImage("优惠卷.png", "close.png", option)
    if (p !== null) {
        tool.log("检测到悬浮窗,开始关闭")
        press(p.x + 20, p.y + 20, 50);
        return true;
    } else {
        return false;
    }
}

//判断是否中奖
function handleLotteryResult() {
    let lotteryResult = false;
    //判断是否中奖
    if (textContains("领取奖品").exists() || textContains("恭喜").exists()) {
        lotteryResult = true;
    } else {
        // tool.log("没有抽中福袋")
    }
    return lotteryResult;
}

//识别当前屏幕的文字
function getText(t) {
    let p = null;
    if (t === undefined || t === null) {
        t = '视频'
    }
    requestScreenCapture(false);
    var img = captureScreen("./image/1.png");
    img = images.read("./image/1.png");
    let res = paddle.ocr(img);
    for (let i = 0; i < res.length; i++) {
        let text = res[i].text
        //tool.log(`文字:${text}-${t}:${text===t}`)
        if (text === t) {
            //tool.log("找到文字：" + JSON.stringify(res[i]));
            p = res[i]
            break;
        }
    }
    return p;
}


//点击当前屏幕内的指定文字
function clickTextByScreenCapture(t) {
    let s = getText(t)
    if (s != null) {
        _press(s['bounds']['left'] + 10, s['bounds']['top'] + 10, 10)
        return true;
    } else {
        return false;
    }
}


//判断界面是否有变化
function isChange() {
    let p = null;
    let option = {
        "region": [0, 0, device.width, device.height],
        "threshold": 0.8
    }
    p = findImage("dqpm2.png", "dqpm.png", option)
    if (p) {
        return true;
    } else {
        return false;
    }
}

exports.setConsole = setConsole;
exports.findImage = findImage;
exports.restartApp = restartApp;
exports.openApp = openApp;
exports.killApp = killApp;
exports.clickId = clickId;
exports.clickText = clickText;
exports.clickDesc = clickDesc;
exports.getScreenCapture = getScreenCapture;
exports.playRingtone = playRingtone;
exports.closeCoupon = closeCoupon;
exports.handleLotteryResult = handleLotteryResult;
exports.clickClassName = clickClassName;
exports.getText = getText;
exports.init = init;
exports.clickTextByScreenCapture = clickTextByScreenCapture;
exports.enterDouYinIndex = enterDouYinIndex;
exports.isChange = isChange;
exports.log = log;
exports.press = _press;
exports.bx = bx;
exports.by = by;